import 'package:flutter/material.dart';
import 'package:groovin_material_icons/groovin_material_icons.dart';
import 'package:jtsell_app/config/app_config.dart';
import 'package:jtsell_app/entity/user_login_entity.dart';
import 'package:jtsell_app/network/http_dispense.dart';
import 'package:jtsell_app/provider/user_login_model.dart';
import 'package:jtsell_app/routes/routes.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:jtsell_app/utils/fluwx_utils.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  var _scaffoldkey = new GlobalKey<ScaffoldState>();

  String _email, _password;
  bool _isObscure = true;
  Color _eyeColor;
  List _loginMethod = [
    {
      "title": "Wechat",
      "icon": GroovinMaterialIcons.wechat,
    },
    {
      "title": "QQ",
      "icon": GroovinMaterialIcons.qqchat,
    },
    {
      "title": "Phone",
      "icon": GroovinMaterialIcons.phone,
    },
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    ///这个方法在一帧的最后调用，并且只调用一次。
    WidgetsBinding.instance.addPostFrameCallback((callback) {

    });
  }

  Widget getChild() {
    return Scaffold(
        key: _scaffoldkey,
        body: Form(
            key: _formKey,
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 22.0),
              children: <Widget>[
                SizedBox(
                  height: kToolbarHeight,
                ),
                buildTitle(),
                //buildTitleLine(),
                SizedBox(height: 70.0),
                buildEmailTextField(),
                SizedBox(height: 30.0),
                buildPasswordTextField(context),
                buildForgetPasswordText(context),
                SizedBox(height: 60.0),
                buildLoginButton(context),
                SizedBox(height: 30.0),
                buildOtherLoginText(),
                buildOtherMethod(context),
                buildRegisterText(context),
              ],
            )));
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<UserLoginModel>.value(value: userLoginModel, child: getChild());
  }

  ///
  /// 跳转到注册页面
  ///
  Align buildRegisterText(BuildContext context) {
    return Align(
      alignment: Alignment.center,
      child: Padding(
        padding: EdgeInsets.only(top: 10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('没有账号？'),
            GestureDetector(
              child: Text(
                '点击注册',
                style: TextStyle(color: AppConfig.THEME_COLOR),
              ),
              onTap: () {
                /// 跳转到注册页面
                Routes.getInstance().registerPage(context).then((res) {
                  Navigator.pop(context);
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  ///
  /// 第三方登录
  ///
  ButtonBar buildOtherMethod(BuildContext context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: _loginMethod
          .map((item) => Builder(
                builder: (context) {
                  return IconButton(
                      icon: Icon(
                        item['icon'],
                        color: AppConfig.THEME_COLOR,
                        size: 25,
                      ),
                      onPressed: () {
                        if (item['title'] == "Wechat") {


                          FluwxUtils.getInstance().wechatAuthListen((String wechatCode) {
                            HttpDispense.wechatLogin(wechatCode).then((UserLoginEntity loginEntity) {
                              print(loginEntity);
                              Provider.of<UserLoginModel>(context).setUserLoginEntity(loginEntity);

                              Navigator.pop(context);
                            });
                          });



                          FluwxUtils.getInstance().wechatLogin();
                        }

                        ///第三方登录方法
//                        SnackBar snackBar = SnackBar(
//                          content: new Text("${item['title']}登录"),
//                          action: new SnackBarAction(
//                            label: "取消",
//                            onPressed: () {},
//                          ),
//                        );
//
//                        _scaffoldkey.currentState.showSnackBar(snackBar);
                      });
                },
              ))
          .toList(),
    );
  }

  ///
  /// 其他账号登录
  ///
  Align buildOtherLoginText() {
    return Align(
        alignment: Alignment.center,
        child: Text(
          '其他账号登录',
          style: TextStyle(color: Colors.grey, fontSize: 14.0),
        ));
  }

  ///
  /// 登录按钮
  ///
  Align buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: 270.0,
        child: RaisedButton(
          child: Text(
            '登录',
            style: Theme.of(context).primaryTextTheme.headline,
          ),
          color: AppConfig.THEME_COLOR,
          onPressed: () {
            if (_formKey.currentState.validate()) {
              ///只有输入的内容符合要求通过才会到达此处
              _formKey.currentState.save();
              //TODO 执行登录方法
              print('email:$_email , assword:$_password');
            }
          },
          shape: StadiumBorder(side: BorderSide(color: Colors.white, width: 0.5)),
        ),
      ),
    );
  }

  ///
  /// 忘记密码
  ///
  Padding buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Align(
        alignment: Alignment.centerRight,
        child: FlatButton(
          child: Text(
            '忘记密码？',
            style: TextStyle(fontSize: 14.0, color: Colors.grey),
          ),
          onPressed: () {
            SnackBar snackBar =
                SnackBar(backgroundColor: AppConfig.THEME_COLOR, content: new Text("暂未实现"));

            _scaffoldkey.currentState.showSnackBar(snackBar);
          },
        ),
      ),
    );
  }

  ///
  /// 密码框
  ///
  TextFormField buildPasswordTextField(BuildContext context) {
    return TextFormField(
      onSaved: (String value) => _password = value,
      obscureText: _isObscure,
      validator: (String value) {
        if (value.isEmpty) {
          return '请输入密码';
        }
      },
      decoration: InputDecoration(
          labelText: '密码',
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = _isObscure ? Colors.grey : AppConfig.THEME_COLOR;
                });
              })),
    );
  }

  ///
  /// 用户名
  ///
  TextFormField buildEmailTextField() {
    return TextFormField(
      decoration: InputDecoration(
        labelText: '账号',
      ),
      validator: (String value) {
//        var emailReg = RegExp(
//            r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
//        if (!emailReg.hasMatch(value)) {
//          return '请输入正确的邮箱地址';
//        }
        if (value == null || value.isEmpty) {
          return "账号不能为空";
        }
      },
      onSaved: (String value) => _email = value,
    );
  }

  Padding buildTitleLine() {
    return Padding(
      padding: EdgeInsets.only(left: 12.0, top: 4.0),
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          color: Colors.black,
          width: 40.0,
          height: 2.0,
        ),
      ),
    );
  }

  Widget buildTitle() {
    return Center(
      child: Text(
        '用户登录',
        style: TextStyle(fontSize: 30.0, color: AppConfig.THEME_COLOR),
      ),
    );
  }
}
